<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2017/12/21
 * Time: 9:47
 */

namespace app\super\controller;
use think\Db;
use  app\super\validate\LifeValidate;

class LifeController extends CommonController
{
    /**
     * 获取生活管理列表数据
     */
    public function getLifeTask(){
        $where = '';
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        if($_POST['keyword']!=''){
            $keyword = $_POST['keyword'];
            $where['a.life_name|u.user_username|u.user_phone'] = array('like',"%$keyword%");
        }
        if($_POST['category']!=''){
            $where['udr.region_name'] = $_POST['category'];
        }
        if($_POST['life_template']!=''){
            $where['a.life_template'] = $_POST['life_template'];
        }
        if($_POST['status']!=''){
            $where['a.life_status'] = $_POST['status'];
        }
        if($_POST['province']!=''){
            $where['a.province'] = $_POST['province'];
        }
        if($_POST['city']!=''){
            $where['a.city'] = $_POST['city'];
        }
        if($_POST['area']!=''){
            $where['a.area'] = $_POST['area'];
        }
        if($_POST['release_status']!=''){
            $where['a.release_status'] = $_POST['release_status'];
        }
        $res = Db::table('up_life')->alias('a')
                                   ->where($where)
                                   ->join('up_u_user u','u.user_id=a.examine_user_id','left')
                                   ->join('up_dic_region udr','udr.region_id = a.category_region_id','left')
                                   ->join('up_team ut','ut.team_id = a.team_id','left')
                                   ->join('up_u_admin uua','uua.user_id = a.examine_user_id','left')
                                   ->field('uua.user_username as username,uua.user_phone as phone,a.*,u.user_username,u.user_phone,udr.region_name,ut.team_name,ut.team_number')
                                   ->limit($rows * ($page - 1), $rows)
                                   ->order('a.life_status desc')
                                   ->select();
        $total = Db::table('up_life')->alias('a')
            ->where($where)
            ->join('up_u_user u','u.user_id=a.examine_user_id','left')
            ->join('up_dic_region udr','udr.region_id = a.category_region_id','left')
            ->join('up_team ut','ut.team_id = a.team_id','left')
            ->join('up_u_admin uua','uua.user_id = a.examine_user_id','left')
            ->count();
        foreach ($res as $key=>&$vo){
            $count = Db::table('up_discuss')->where('life_id',$vo['life_id'])->count();
            $vo['count'] = $count;
        }
        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }

    /**
     * 发布
     */
    public function FbLife(){
        $cid = $_POST['cid'];
        if($cid!=''){
            $where['life_id'] = $cid;
            $data['release_status'] = 1;//审核通过
            $data['examine_user_id'] = session('loginSession')['user_id'];//审核人UUID
            $res =  Db::table('up_life')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "发布成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "发布失败";
                return json_encode($returnData);
            }
        }
    }
    /***
     * 取消发布
     */
    public function QxLife(){
        $cid = $_POST['cid'];
        if($cid!=''){
            $where['life_id'] = $cid;
            $data['release_status'] = 2;
            $data['examine_user_id'] = session('loginSession')['user_id'];//审核人UUID
            $res =  Db::table('up_life')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "发布成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "发布失败";
                return json_encode($returnData);
            }
        }
    }
    /**
     * 审核通过
     */
    public function updateLife(){
        $cid = $_POST['cid'];
        if($cid!=''){
            $where['life_id'] = $cid;
            $data['life_status'] = 1;//审核通过
            $data['examine_user_id'] = session('loginSession')['user_id'];//审核人UUID
            $res =  Db::table('up_life')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "审核成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "审核失败";
                return json_encode($returnData);
            }
        }
    }

    /**
     *审核不通过
     */
    public function refuseLife(){
        $cid = $_POST['cid'];
        if($cid!=''){
            $where['life_id'] = $cid;
            $data['life_status'] = 2;//审核通过
            $data['examine_user_id'] = session('loginSession')['user_id'];//审核人UUID
            $res =  Db::table('up_life')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "审核成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "审核失败";
                return json_encode($returnData);
            }
        }
    }
    /**
     * 删除此公共
     */
    public function deleteLife(){

        $cid = $_POST['cid'];
        if($cid!=''){
            $where['life_id'] = $cid;
            $res =  Db::table('up_life')->where($where)->delete();
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "删除成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "删除失败";
                return json_encode($returnData);
            }
        }
    }
    /**
     * 公众信息详情
     */
//    public function courseInfo(){
//        $cid = $_POST['cid'];
//        if($cid!=''){
//            $where['life_id'] = $cid;
//            $res = Db::table('up_life')->where($where)->field('life_name,life_content,img_url')->find();
//            $img_url = explode(',',$res['img_url']);
//            $this->assign('res',$res);
//            $this->assign('img_url',$img_url);
//        }
//        return $this->fetch('life/detail');
//    }

    /**
     * 查询省
     */
    public function province(){
        $province = Db::table('up_area')->where('level',1)->select();
        $data['province'] = $province;
        return json_encode($province);
    }
    /**
     * 查询市
     */
    public function city(){
        $city = $_POST['city'];
        $cityArray = Db::table('up_area')->where('pid',$city)->select();
        $data['cityArray'] = $cityArray;
        return json_encode($data);
    }
    /**
     * 查询区
     */
    public function area(){
        $area = $_POST['area'];
        $cityArray = Db::table('up_area')->where('pid',$area)->select();
        $data['cityArray'] = $cityArray;
        return json_encode($data);
    }

    /**
     * 添加列表页面
     */
    public function addLife(){
//        $res1 = array();
//        $team_id = Db::table('up_team')->where('is_team',1)->column('team_id');
//        $team= Db::table('up_team')->where('is_team',1)->field('team_id,team_name')->select();
//        $this->assign('team',$team);

//        if(count($team_id)>0){
//            $where['team_id'] = array('IN',$team_id);
//            $res1 = Db::table('up_team_members')->alias('a')
//                ->join('up_u_user uuu','uuu.user_id = a.team_member_user_id')
//                ->field('uuu.user_id,uuu.user_phone,uuu.user_username')
//                ->where($where)
//                ->select();
//        }
//        $this->assign('res1',$res1);
        $province = Db::table('up_area')->where('level',1)->select();
        $where['region_fid']='ZDvaTNytyem97oNtRh692WpwYW8C3YPr';
        $res = Db::table('up_dic_region')->where($where)->select();//查询字典表里面的属于生活管理的子分类
        $this->assign('province',$province);
        $this->assign("res",$res);
        return $this->fetch('life/addLife');
    }

    public function insertLifePic()
    {
        $who = $_POST['who'];
        $name = $_FILES["thumb{$who}"]['name'];
        $name = explode('.',$name);
        $date = date('YmdHis');
        $rand = rand(100000,999999);
        $aa = $date . $rand . '.' . $name[1];
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($name[1] != 'jpg' && $name[1] != 'png' && $name[1] != 'gif'){
            return json_encode(['status'=>0,'msg'=>'上传的图片格式不支持']);
        }
        if(!empty($_FILES["thumb{$who}"]['tmp_name'])){
            if(move_uploaded_file($_FILES["thumb{$who}"]['tmp_name'],"{$dir}/upload/{$aa}")){
                $msg = "{$url}/upload/{$aa}";
                $this->image_png_size_add("{$dir}/upload/{$aa}","{$dir}/upload/{$aa}");
                return json_encode(['status'=>200,'msg'=>$msg,'idid'=>$date.$rand]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'获取不到图片信息']);
        }
    }
    /*
     * 添加信息
     */
    public function insertLife(){
        $uid = session('loginSession')['user_id'];
        $file_name = $_FILES['file']['name']; //文件名字
        $url_img = '';
        $file_array = array();//定义空数组
        $validata = new LifeValidate();

        if(!$validata->check($_POST)){
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        }else{
            if(mb_strlen($_POST['life_name'],"utf-8")>30){
                $returnData['status'] = 0;
                $returnData['msg'] = "信息名称不能超过30个";
                return json_encode($returnData);
            }
            if ($_POST['template'] == 2) {//上传3张图片信息
                if ($_FILES['file']['name'][0] == '' || $_FILES['file']['name'][1] == '' || $_FILES['file']['name'][2] == '') {
                    $returnData['status'] = 0;
                    $returnData['msg'] = "信息模板和上传图片张数不相符合";
                    return json_encode($returnData);
                } else {
                    $rand = date('YmdHis') . rand(100000, 999999);
                    $exe = explode('.', $_FILES['file']['name'][0]);
                    $filePath = $_FILES['file']['tmp_name'][0];
                    $info = $this->qnCommon(2, $rand, $exe[1], $filePath);
                    if ($info['status'] == 200) {
                        $file_array[0] = QiNiu . $info['key'];
                    }
                    $rand1 = date('YmdHis') . rand(100000, 999999);
                    $exe1 = explode('.', $_FILES['file']['name'][1]);
                    $filePath1 = $_FILES['file']['tmp_name'][1];
                    $info1 = $this->qnCommon(2, $rand1, $exe1[1], $filePath1);
                    if ($info1['status'] == 200) {
                        $file_array[1] = QiNiu . $info1['key'];
                    }
                    $rand2 = date('YmdHis') . rand(100000, 999999);
                    $exe2 = explode('.', $_FILES['file']['name'][2]);
                    $filePath2 = $_FILES['file']['tmp_name'][2];
                    $info2 = $this->qnCommon(2, $rand2, $exe2[1], $filePath2);
                    if ($info2['status'] == 200) {
                        $file_array[2] = QiNiu . $info2['key'];
                    }
                    if($info['status']!=200||$info1['status']!=200||$info2['status']!=200){
                        $returnData['status'] = 0;
                        $returnData['msg'] = "上传图片格式不对";
                        return json_encode($returnData);
                    }
                    $url_img = implode(',',$file_array);//切割成字符串
                }
            }else{//上传一张图的信息
                $rand = date('YmdHis') . rand(100000, 999999);
                $exe = explode('.', $_FILES['file']['name'][0]);
                $filePath = $_FILES['file']['tmp_name'][0];
                $info = $this->qnCommon(2, $rand, $exe[1], $filePath);
                if ($info['status'] == 200) {
                    $url_img = QiNiu . $info['key'];
                }
            }
            $data['img_url'] = $url_img;

            if(isset($_POST['insert_image'])){
            $img_array = $_POST['insert_image'];
            if($img_array){
                $data['content_url']=implode(',',$img_array);
            }
        }

        $data['category_region_id'] = $_POST['region_name'];
        $data['life_name'] = $_POST['life_name'];
        $data['life_template'] = $_POST['template'];
        $data['life_time'] = date('Y-m-d H:i:s');
        $data['province'] = $_POST['province'];
        $data['city'] = $_POST['city'];
        $data['area'] = $_POST['area'];
        $data['life_content'] = $_POST['content']?$_POST['content']:'';
        $data['life_id'] = $this->getRandChar(32);//创建32位ID
        $data['life_status'] = 1;
        if(isset($_POST['knowledge_team_id'])){
            $data['team_id'] = $_POST['knowledge_team_id'];
        }

        $data['publisher_uid_id'] = session('loginSession')['user_id'];
        $data['examine_user_id'] = session('loginSession')['user_id'];//证明审核人就是自己
        $province = Db::table('up_area')->where('district_id',$_POST['province'])->value('district');//查询省
        $city = Db::table('up_area')->where('district_id',$_POST['city'])->value('district');//查询市
        $area = Db::table('up_area')->where('district_id',$_POST['area'])->value('district');//查询区
        $data['pca'] = $province.'-'.$city.'-'.$area;

        $res = Db::table('up_life')->insert($data);
        }

        if($res){
            $whereU['user_status'] = 1;
            $up_u_user =Db::table('up_u_user')->where($whereU)->column('user_id');
            $msg1 = "{\"msg\":\"22\"}";
            $msg = '平台发布了一条生活公众信息，快去查看！';
            $msg_data = array('msg'=>$msg,'code'=>22,'fid'=>$data['life_id']);
            $code = 22;
            $code1 = 22;
            $this->sendJpush(2,$msg,$msg_data,$up_u_user,$msg1,$code,1,$code1);
            return json_encode(array("status" => 1, "msg" => "发布成功！"));
        }else{
            return json_encode(array("status" => 0, "msg" => "发布失败！"));
        }
    }

    /***
     * 修改页面
     */
    public function updateLifeInfo(){
        $nid = $_POST['nid'];
        $res = Db::table('up_life')->where('life_id',$nid)->find();
        $res['img_url']=explode(',',$res['img_url']);
        $province = Db::table('up_area')->where('level',1)->select();
        $pid = Db::table('up_area')->where('district_id',$res['city'])->value('pid');//先根据市查询省ID
        $city =Db::table('up_area')->where('pid',$pid)->field('district_id,district')->select();
        $res['province']=$pid;
        $area =Db::table('up_area')->where('pid',$res['city'])->field('district_id,district')->select();
        $where['region_fid'] = 'ZDvaTNytyem97oNtRh692WpwYW8C3YPr';
        $config = Db::table('up_dic_region')->where($where)->select();
        //编辑对应的处理——6张详情图
        $for_loop = array(4,5,6,7,8,9);
        $sixid = array();
        $sixsrc = array();
        $sixhave = array();
        $next = 4;
        $isten = 4;
        if($res['content_url']){
            $six = explode(',',$res['content_url']);
            $i = 4;
            foreach ($six as $v){
                $sixsrc[$i] = $v;
                $vv = explode('/',$v);
                $count = count($vv);
                $vvv = $vv[$count-1];
                $vvvv = explode('.',$vvv);
                $sixid[$i] = $vvvv[0];
                $sixhave[] = $i;
                $i++;
                $next = $i;
                $isten = $i;
            }
        }
        if($next > 9){$next = 4;}
        $this->assign('for_loop',$for_loop);
        $this->assign('sixid',$sixid);
        $this->assign('sixsrc',$sixsrc);
        $this->assign('sixhave',$sixhave);
        $this->assign('next',$next);
        $this->assign('isten',$isten);
        //编辑对应的处理——6张详情图
        $this->assign('res',$res);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->assign('config_list',$config);
        return $this->fetch('life/updateLifeInfo');
    }

    /**
     * 编辑功能
     */
    public function updateLifeList(){
        $uid = session('loginSession')['user_id'];
        $file_name = $_FILES['file']['name']; //文件名字
        $where['life_id'] = $_POST['life_id'];
        $img_url = Db::table('up_life')->where($where)->field('img_url,life_template')->find();//查询图片信息
        $img_url_list = explode(',',$img_url['img_url']);
        $validata = new LifeValidate();
        if(!$validata->check($_POST)){
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        }else{
            if(mb_strlen($_POST['life_name'],"utf-8")>30){
                $returnData['status'] = 0;
                $returnData['msg'] = "信息名称不能超过30个";
                return json_encode($returnData);
            }
            //判断模板是1或者3的情况下
            if($_POST['template']==1||$_POST['template']==3){
                if(!empty($file_name[0])){//证明是上传新的图片了
                    $rand = date('YmdHis').rand(100000,999999);
                    $exe = explode('.',$_FILES['file']['name']);
                    $filePath = $_FILES['file']['tmp_name'];
                    $info = $this->qnCommon(2,$rand,$exe[1],$filePath);
                    if($info['status']==200){
                        $data['img_url'] = QiNiu.$info['key'];
                    }
                }else{
                    if($img_url['life_template']==2){//如果是原来的模板是上传3张图片,删除数组的第2个和第3个元素值
                        unset($img_url_list[1]);
                        unset($img_url_list[2]);
                    }
                }
            }else{
                //循环3次
                if($img_url['life_template']==2){//原来的模板是2上传3张图片的时候
                    for ($i=0;$i<3;$i++){
                        if(!empty($file_name[$i])){
                            $rands = date('YmdHis').rand(100000,999999);
                            $exes = explode('.',$file_name[$i]);
                            $filePaths = $file_name[$i];
                            $info = $this->qnCommon(2,$rands,$exes[1],$filePaths);
                            if($info['status']==200){
                                $img_url_list[$i] = QiNiu.$info['key'];
                            }
                        }
                    }
                }else{//原来的模板是1或者3的情况
                    if($_FILES['file']['tmp_name'][0]!=''){
                        $rand = date('YmdHis') . rand(100000, 999999);
                        $exe = explode('.', $_FILES['file']['name'][0]);
                        $filePath = $_FILES['file']['tmp_name'][0];
                        $info = $this->qnCommon(2, $rand, $exe[1], $filePath);
                        if ($info['status'] == 200) {
                            $img_url_list[0] = QiNiu . $info['key'];
                        }else{
                            $returnData['status'] = 0;
                            $returnData['msg'] = "上传图片格式不对";
                            return json_encode($returnData);
                        }
                    }

                    $rand1 = date('YmdHis') . rand(100000, 999999);
                    $exe1 = explode('.', $_FILES['file']['name'][1]);
                    $filePath1 = $_FILES['file']['tmp_name'][1];
                    $info1 = $this->qnCommon(2, $rand1, $exe1[1], $filePath1);
                    if ($info1['status'] == 200) {
                        $img_url_list[1] = QiNiu . $info1['key'];
                    }else{
                        $returnData['status'] = 0;
                        $returnData['msg'] = "上传图片格式不对";
                        return json_encode($returnData);
                    }
                    $rand2 = date('YmdHis') . rand(100000, 999999);
                    $exe2 = explode('.', $_FILES['file']['name'][2]);
                    $filePath2 = $_FILES['file']['tmp_name'][2];
                    $info2 = $this->qnCommon(2, $rand2, $exe2[1], $filePath2);
                    if ($info2['status'] == 200) {
                        $img_url_list[2] = QiNiu . $info2['key'];
                    }else{
                        $returnData['status'] = 0;
                        $returnData['msg'] = "上传图片格式不对";
                        return json_encode($returnData);
                    }
                }
            }
        if(isset($_POST['insert_image'])){
            $img_array = $_POST['insert_image'];
            if($img_array){
                $data['content_url']=implode(',',$img_array);
            }
        }
        $url_img = implode(',',$img_url_list);//切割成字符串
        $data['category_region_id'] = $_POST['region_name'];
        $data['life_name'] = $_POST['life_name'];
        $data['life_template'] = $_POST['template'];
        $data['life_time'] = date('Y-m-d H:i:s');
        $data['img_url'] = $url_img;
        $data['province'] = $_POST['province'];
        $data['city'] = $_POST['city'];
        $data['area'] = $_POST['area'];
        $data['publisher_uid_id'] = $uid;
        $data['life_content'] = $_POST['content']?$_POST['content']:'';
        $data['life_status'] = 1;
        $data['examine_user_id'] = $uid;//证明审核人就是自己
        $province = Db::table('up_area')->where('district_id',$_POST['province'])->value('district');//查询省
        $city = Db::table('up_area')->where('district_id',$_POST['city'])->value('district');//查询市
        $area = Db::table('up_area')->where('district_id',$_POST['area'])->value('district');//查询区
        $data['pca'] = $province.'-'.$city.'-'.$area;

        $res = Db::table('up_life')->where($where)->update($data);
        if($res){
            return json_encode(array("status" => 1, "msg" => "修改成功！"));
        }else{
            return json_encode(array("status" => 0, "msg" => "修改失败！"));
        }
    }
    }
}